package utils

import (
	"fmt"
	"github.com/go-xorm/xorm"
	"github.com/spf13/viper"
	"src/config"
	"xorm.io/core"
)

// 使用示例
// db := utils.NewDbClient("db", nil)
// //// 创建新用户记录
// user := model.FangUser{}
// has, _ := db.Client.Where("uid=?", "848593").Get(&user)
// if has {
// println(user.Nick, user.FangId)
// }
type DbClient struct {
	Name   string
	Client *xorm.Engine
	Config *DbConfig
}
type DbConfig struct {
	username string
	//连接数据库的密码
	password string
	//连接数据库的地址
	ip string
	//连接数据库的端口号
	port int
	//连接数据库的具体数据库名称
	dbname string
	//连接数据库的编码格式
	charset string
}

func DbConf() *DbConfig {
	return &DbConfig{
		username: viper.GetString("db.mysql.conf.username"),
		//连接数据库的密码
		password: viper.GetString("db.mysql.conf.password"),
		//连接数据库的地址
		ip: viper.GetString("db.mysql.conf.ip"),
		//连接数据库的端口号
		port: viper.GetInt("db.mysql.conf.port"),
		//连接数据库的具体数据库名称
		dbname: viper.GetString("db.mysql.conf.dbname"),
		//连接数据库的编码格式
		charset: viper.GetString("db.mysql.conf.charset"),
	}
}

func NewDbClient(name string, conf *DbConfig) *DbClient {
	if conf == nil {
		conf = DbConf()
	}
	//client :=DB(userName string, password string, ipAddress string, port int, dbName string, charset string)
	client := &DbClient{Name: name, Config: conf}
	_, err := client.Db(conf.username, conf.password, conf.ip, conf.port, conf.dbname, conf.charset)
	if err != nil {
		return nil
	}
	return client
}

func (this *DbClient) Db(userName string, password string, ipAddress string, port int, dbName string, charset string) (db *xorm.Engine, err error) {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s", userName, password, ipAddress, port, dbName, charset)
	engine, err := xorm.NewEngine("mysql", dsn)
	if err != nil {
		fmt.Println("校验失败,err", err)
		//panic("failed to connect to database")
		return nil, err
	}
	debug := config.V().GetBool("debug")
	if debug {
		engine.ShowSQL(config.V().GetBool("debug"))
		engine.Logger().SetLevel(core.LOG_DEBUG)
	}
	prefix := config.V().GetString("db.mysql.conf.prefix")
	tbMapper := core.NewPrefixMapper(core.SnakeMapper{}, prefix)
	engine.SetTableMapper(tbMapper)
	this.Client = engine
	return engine, err
	//user := &User{Token: "2c40ea7e0d361fb9c39b3b974043987d"}
	////查询方法
	//has, err := engine.Get(user)
	//if has {
	//	println(user.Name)
	//}
	// 自动创建数据库表结构
	//err = engine.Sync2(new(User))
	//if err != nil {
	//	panic("failed to create table")
	//}
	//
	//// 创建新用户记录
	//user := User{Name: "John Doe", Token: "john@example.com"}
	//affected, err := engine.Insert(&user)
	//if err != nil || affected == 0 {
	//	panic("failed to create user")
	//}
}
